package com.feeyin.radar.crm.service.impl;

import com.feeyin.radar.commons.DateUtils;
import com.feeyin.radar.commons.FinalUtils;
import com.feeyin.radar.commons.StringUtils;
import com.feeyin.radar.crm.model.SalePeriodReport;
import com.feeyin.radar.crm.service.EmployeeManageService;
import com.feeyin.radar.sys.dao.BusinessTargetDAO;
import com.feeyin.radar.sys.dao.DepartmentDAO;
import com.feeyin.radar.sys.dao.UserDAO;
import com.feeyin.radar.sys.model.BusinessTarget;
import com.feeyin.radar.sys.model.Department;
import com.feeyin.radar.sys.model.Users;
import java.io.FileOutputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class EmployeeManageServiceImpl
  implements EmployeeManageService
{
  private UserDAO userDAO;
  private DepartmentDAO departmentDAO;
  private BusinessTargetDAO businessTargetDAO;

  public UserDAO getUserDAO()
  {
    return this.userDAO;
  }

  public void setUserDAO(UserDAO userDAO) {
    this.userDAO = userDAO;
  }

  public DepartmentDAO getDepartmentDAO() {
    return this.departmentDAO;
  }

  public void setDepartmentDAO(DepartmentDAO departmentDAO) {
    this.departmentDAO = departmentDAO;
  }

  public BusinessTargetDAO getBusinessTargetDAO() {
    return this.businessTargetDAO;
  }

  public void setBusinessTargetDAO(BusinessTargetDAO businessTargetDAO) {
    this.businessTargetDAO = businessTargetDAO;
  }

  public List getEmployeesByDeptIds(Integer deptId, Integer currentUserId)
  {
    if (deptId == null) return null;
    if (currentUserId == null) return null;
    int sign = isUserDeptOrSubDept(currentUserId, deptId);
    if (sign == 0) return null;

    String deptIds = this.departmentDAO.getCurrentDeptIdAndSubDeptIdsByDeptId(deptId);
    if (StringUtils.isEmpty(deptIds)) return null;
    List list = new ArrayList();
    Users pUser = new Users();
    pUser.setDeptIds(deptIds);
    pUser.setIsActivity("1");
    list = this.userDAO.getUsersByDynamic(pUser);
    if ((list == null) || (list.size() <= 0)) return null;

    for (int i = 0; i < list.size(); i++) {
      Users user = new Users();
      user = (Users)list.get(i);

      Department dept = new Department();
      dept = this.departmentDAO.getDepartment(user.getDeptId());
      if (dept != null) {
        user.setDeptName(dept.getDeptName());
      }

      BigDecimal assignTarget = new BigDecimal(0);
      assignTarget = this.businessTargetDAO.getYearTargetBySalePersonId(user.getId());
      if ((assignTarget != null) && (assignTarget.compareTo(new BigDecimal(0)) > 0)) {
        assignTarget = assignTarget.divide(new BigDecimal(1), 0, 4);
      }
      user.getBusinessTarget().setTotalTarget(assignTarget);

      BigDecimal[] finishedTarget = new BigDecimal[2];
      finishedTarget = this.businessTargetDAO.getFinishedTarget(user.getId(), "3");
      if ((finishedTarget != null) && (finishedTarget[0] != null))
      {
        user.getSalePeriodReport().setFinishCost(finishedTarget[0]);
      }

      String isFinishedTarget = "0";
      if ((assignTarget != null) && (assignTarget.compareTo(new BigDecimal(0)) > 0)) {
        if ((finishedTarget != null) && (finishedTarget[0] != null) && (finishedTarget[0].compareTo(new BigDecimal(0)) > 0)) {
          BigDecimal temp = new BigDecimal(0);
          temp = finishedTarget[0].divide(assignTarget, 12, 4);
          if ((temp != null) && (temp.compareTo(new BigDecimal(0)) > 0)) {
            temp = temp.multiply(new BigDecimal(100));
            user.getSalePeriodReport().setFinishRate(temp);
          }

          if (finishedTarget[0].compareTo(assignTarget) >= 0) {
            isFinishedTarget = "1";
          }
        }
        user.setIsFinishedTarget(isFinishedTarget);
      }
    }
    return list;
  }

  public List getEmployeeLevels() {
    List departments = new ArrayList();
    departments = this.departmentDAO.getDepartments();

    if ((departments == null) || (departments.size() <= 0)) return null;
    for (int i = 0; i < departments.size(); i++) {
      Department department = new Department();
      department = (Department)departments.get(i);

      Users user = new Users();

      user.setDeptId(department.getId());
      user.setIsActivity("1");
      List users = new ArrayList();
      users = this.userDAO.getUsersByDynamic(user);
      if ((users != null) || (users.size() > 0)) {
        department.getUsers().addAll(users);
      }
    }

    return departments;
  }

  public boolean saveWaitExportFile(String realPath, Integer currentUserId)
  {
    if (StringUtils.isEmpty(realPath)) return false;
    if (currentUserId == null) return false;
    List users = new ArrayList();
    users = this.userDAO.getActivityUsers();
    if ((users == null) || (users.size() < 0)) return false;
    String basePath = realPath + "upload" + System.getProperty("file.separator") + "temp";
    String storedPath = basePath + System.getProperty("file.separator") + "employeeLevel" + currentUserId + ".xls";
    try
    {
      FileOutputStream fos = new FileOutputStream(storedPath);
      HSSFWorkbook wb = new HSSFWorkbook();
      HSSFSheet s = wb.createSheet();
      wb.setSheetName(0, "sheet1");
      HSSFRow row = s.createRow(0);

      HSSFFont fontStyle = wb.createFont();

      fontStyle.setFontHeightInPoints((short)12);
      fontStyle.setBoldweight((short)700);

      HSSFCellStyle cellStyle = wb.createCellStyle();
      cellStyle.setFillForegroundColor((short)12);
      cellStyle.setFont(fontStyle);
      cellStyle.setFillPattern((short)1);

      s.setDefaultColumnWidth((short)18);

      HSSFCell cell = row.createCell((short)0);
      cell.setCellStyle(cellStyle);
      cell.setCellValue("所属部门");
      cell.setCellStyle(cellStyle);
      cell = row.getCell((short)1);
      cell.setCellValue("姓名");
      cell.setCellStyle(cellStyle);
      cell = row.getCell((short)2);
      cell.setCellValue("信用等级");
      cell.setCellStyle(cellStyle);
      cell = row.getCell((short)3);
      cell.setCellValue("办公电话");
      cell.setCellStyle(cellStyle);
      cell = row.getCell((short)4);
      cell.setCellValue("手机");
      cell.setCellStyle(cellStyle);
      cell = row.getCell((short)5);
      cell.setCellValue("生日");
      cell.setCellStyle(cellStyle);
      cell = row.getCell((short)6);
      cell.setCellStyle(cellStyle);
      cell.setCellValue("电子邮件");
      for (int i = 0; i < users.size(); i++) {
        Users user = new Users();
        user = (Users)users.get(i);
        row = s.createRow(i + 1);
        cell = row.getCell((short)0);
        String deptName = "";
        if (user.getDeptId() != null) {
          Department department = new Department();
          department = this.departmentDAO.getDepartment(user.getDeptId());
          if (department != null) {
            deptName = department.getDeptName();
          }
        }
        cell.setCellValue(deptName);
        cell = row.getCell((short)1);
        cell.setCellValue(user.getUserName());
        cell = row.getCell((short)2);
        String levelName = "";
        if (user.getCreditLevel() != null) {
          if (user.getCreditLevel().compareTo(Integer.valueOf(1)) == 0)
            levelName = FinalUtils.LEVEL1;
          else if (user.getCreditLevel().compareTo(Integer.valueOf(2)) == 0)
            levelName = FinalUtils.LEVEL2;
          else if (user.getCreditLevel().compareTo(Integer.valueOf(3)) == 0)
            levelName = FinalUtils.LEVEL3;
          else if (user.getCreditLevel().compareTo(Integer.valueOf(4)) == 0)
            levelName = FinalUtils.LEVEL4;
          else if (user.getCreditLevel().compareTo(Integer.valueOf(5)) == 0) {
            levelName = FinalUtils.LEVEL5;
          }
        }
        cell.setCellValue(levelName);
        cell = row.getCell((short)3);
        cell.setCellValue(user.getSubPhone());
        cell = row.getCell((short)4);
        cell.setCellValue(user.getMobile());
        cell = row.getCell((short)5);
        cell.setCellValue(DateUtils.getStringDateByFormat(user.getBirthday(), "yyyy-MM-dd"));
        cell = row.getCell((short)6);
        cell.setCellValue(user.getEmail());
      }

      wb.write(fos);
      fos.close();
      return true;
    } catch (Exception e) {
      e.printStackTrace();
    }
    return false;
  }

  public boolean updateEmployeeLevel(Integer userId, int sign) {
    if (userId == null) return false;
    Users oldUser = new Users();
    oldUser = this.userDAO.getUser(userId);

    if (oldUser == null) return false;
    Users user = new Users();
    user.setId(oldUser.getId());
    if (sign == 0)
      user.setCreditLevel(Integer.valueOf(oldUser.getCreditLevel().intValue() - 1));
    else if (sign == 1) {
      user.setCreditLevel(Integer.valueOf(oldUser.getCreditLevel().intValue() + 1));
    }
    return this.userDAO.updateUserByDynamic(user);
  }

  private int isUserDeptOrSubDept(Integer currentUserId, Integer selectDeptId)
  {
    if (currentUserId == null) return 0;
    if (selectDeptId == null) return 0;
    Users curUser = new Users();
    curUser = this.userDAO.getUser(currentUserId);
    if (curUser == null) return 0;

    if (curUser.getDeptId() == null) return 0;
    Department department = new Department();
    department = this.departmentDAO.getDepartment(curUser.getDeptId());

    if (department == null) return 0;
    List subDepts = new ArrayList();
    subDepts = this.departmentDAO.getDepartmentByDeptSeq(department.getDeptSeq());

    if ((subDepts == null) || (subDepts.size() <= 0)) return 0;
    int sign = 0;
    for (int i = 0; i < subDepts.size(); i++) {
      Department dept = new Department();
      dept = (Department)subDepts.get(i);
      if (selectDeptId.compareTo(dept.getId()) == 0) {
        sign = 1;
        break;
      }
    }
    return sign;
  }
}